﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.Security.Principal;

namespace Sinacor.Infra.Service.Security.Authorization
{
    /// <summary>
    /// Responsável pela Autorização dos Tokens Sinacor.
    /// </summary>
    public class SinacorAuthorizationPolicy : IAuthorizationPolicy, IAuthorizationComponent
    {
        string id;
        ClaimSet tokenClaims;
        ClaimSet issuer;

        /// <summary>
        /// Construtor
        /// </summary>
        /// <param name="tokenClaims">ClaimSet contendo a lista de claims do usuário</param>
        public SinacorAuthorizationPolicy(ClaimSet tokenClaims)
        {
            if (tokenClaims == null)
            {
                throw new ArgumentNullException("tokenClaims");
            }

            //Define o emissor dos tokens como System
            this.issuer = ClaimSet.System;
            //Define os tokenClaims recebidos do Authenticator, para definir no contexto.
            this.tokenClaims = tokenClaims;
            //Gera um novo Id para o Policy
            this.id = Guid.NewGuid().ToString();
        }

        #region IAuthorizationPolicy Members

        public bool Evaluate(EvaluationContext evaluationContext, ref object state)
        {
            //Adiciona as claims ao contexto.
            evaluationContext.AddClaimSet(this, tokenClaims);
            
            return true;
        }

        public System.IdentityModel.Claims.ClaimSet Issuer
        {
            get { return issuer; }
        }

        #endregion

        #region IAuthorizationComponent Members

        public string Id
        {
            get { return id; }
        }

        #endregion
    }
}
